package com.test.demo;

/**
 * Created by jl on 2017/11/9.
 */
public class MyLinkedList<T> {

    private static class Node<T> {
        Node<T> pre;
        Node<T> next;
        T data;

        public Node(Node<T> pre, Node<T> next, T data) {
            this.pre = pre;
            this.next = next;
            this.data = data;
        }

        public Node(T data) {
            this.data = data;
        }

        boolean hasNext() {
            return null != this.next;
        }
    }

    private Node<T> head;

    /**
     * 插入，从位置0开始
     */
    public void insert(T t, int pos) {
        if (null == head) {
            head = new Node<T>(null, null, t);
            return;
        }
        Node<T> newNode = new Node<T>(t);
        Node<T> node = head;
        //插入的位置小于1，则插在最前面
        if (pos < 1) {
            newNode.next = node;
            node.pre = newNode;
            head = newNode;
            return;
        }
        //插入位置在中间
        int i = 1;
        while (node.hasNext()) {
            node = node.next;
            if (i++ == pos) {
                newNode.pre = node.pre;
                node.pre.next = newNode;
                node.pre = newNode;
                newNode.next = node;
                return;
            }
        }
        //插入的位置超过了当前最大位置，则插在最后
        if (null == newNode.pre) {
            node.next = newNode;
            newNode.pre = node;
        }
    }

    public void print() {
        Node<T> node = head;
        if (null == head) {
            return;
        }
        System.out.println(node.data.toString());
        while (node.hasNext()) {
            node = node.next;
            System.out.println(node.data.toString());
        }
    }

    public static void main(String[] args) {
        MyLinkedList<String> linkedList = new MyLinkedList<String>();
        linkedList.insert("jl", 0);
        linkedList.insert("dsy", 1);
        linkedList.insert("wjl", 1);
        linkedList.insert("csy", -1);
        linkedList.insert("hzl", 100);
        linkedList.print();
    }
}
